package com.spark.async.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Future;

//注意：1、要把异步任务写进一个类里面而不能直接写在controller中
//      2、如果需要拿到结果，则需要在调用处判断全部的task.isDone()来确定异步任务的完成
@org.springframework.stereotype.Service
//异步类注解，表明整个类的方法都是异步方法，如果把这个注解加在某一个方法上而不是某一个类则表明仅仅是这个方法才是异步方法
@Async
public class Service {
    //下面是3个异步任务（不带返回值的）
    public void task1() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        System.out.println("任务1耗时" + (end - begin));
    }

    public void task2() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(2000L);
        long end = System.currentTimeMillis();
        System.out.println("任务2耗时" + (end - begin));
    }

    public void task3() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(1000L);
        long end = System.currentTimeMillis();
        System.out.println("任务3耗时" + (end - begin));
    }

    //下面是3个异步任务（带返回值的，可以在调用出取地返回值）
    public Future<String> task4() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(300L);
        long end = System.currentTimeMillis();
        return new AsyncResult<String>("任务4耗时" + (end - begin));
    }

    public Future<String> task5() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(200L);
        long end = System.currentTimeMillis();
        return new AsyncResult<String>("任务5耗时" + (end - begin));
    }

    public Future<String> task6() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(100L);
        long end = System.currentTimeMillis();
        return new AsyncResult<String>("任务6耗时" + (end - begin));
    }

    public ListenableFuture<String> task7() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(100L);
        long end = System.currentTimeMillis();
        if (2 % 2 == 0) {
            return AsyncResult.forExecutionException(new RuntimeException("故意失败！"));
        }
        return new AsyncResult<String>("任务7耗时" + (end - begin));
    }

    public void task8() throws InterruptedException {
        long begin = System.currentTimeMillis();
        Thread.sleep(3000L);
        long end = System.currentTimeMillis();
        if (2 % 2 == 0) {
            throw new RuntimeException("故意失败！");
        }
        System.out.println("任务8耗时" + (end - begin));
    }
}
